import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
// import Login from '@/views/login'
// import Layout from '@/views/layout'
// import NotFound from '@/views/404'
// import Search from '@/views/search'
// import SearchResult from '@/views/search/result'
// import Edit from '@/views/layout/user/edit.vue'
// import Article from '@/views/article'
// import Home from '@/views/layout/home'
// import Video from '@/views/layout/video'
// import Qa from '@/views/layout/qa'
// import User from '@/views/layout/user'

// import Chat from '@/views/layout/user/chat'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: () => import('@/views/layout'),
    redirect: '/home',
    children: [
      {
        path: 'home',
        component: () => import('@/views/layout/home'),
        meta: {
          // !首页路由对应的组件是需要被缓存起来的
          isKeepLive: true
        }
      },
      {
        path: 'video',
        component: () => import('@/views/layout/video')
      },
      {
        path: 'qa',
        component: () => import('@/views/layout/qa')
      },
      {
        path: 'user',
        component: () => import('@/views/layout/user')
      }
    ]
  },
  {
    path: '/login',
    component: () => import('@/views/login')
  },
  {
    path: '/search',
    component: () => import('@/views/search')
  },
  {
    path: '/search/result',
    component: () => import('@/views/search/result')
  },
  {
    path: '/detail/:id',
    component: () => import('@/views/article')
  },
  {
    path: '/user/edit',
    component: () => import('@/views/layout/user/edit.vue')
  },
  {
    path: '/user/chat',
    component: () => import('@/views/layout/user/chat')
  },
  {
    path: '*',
    component: () => import('@/views/404')
  }
]

const router = new VueRouter({
  routes
})

// 全局导航守卫(访问权限)
// !需要拦截的页面(需要登录才可以访问到)
const loginURL = ['/user', '/user/edit']
router.beforeEach((to, from, next) => {
  const token = store.state.user.token.token
  if (token) {
    next()
  } else {
    if (loginURL.some((item) => to.path === item)) {
      // 成立跳到login
      // next('/login') //!导航故障报错(改为以下写法)
      // router.push('/login')
      // !活的写法
      router.push({
        path: '/login',
        query: {
          back: to.fullPath
        }
      })
    } else {
      next()
    }
  }
})

export default router
